/**
 * 普通相册
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    var dialog = require("dialog");
    require("pagination");
    require("permission");
    var plupload = require("plupload");
    
    var api_prefix = G_CONFIG["api_prefix"] + "tools/basis-function-plugin/"; //api前缀

    var album = {
        list:[],
        pagerInited:false,
        pageIndex:1,
        pageSize:7,
        //相册列表
        photoPagerInited:false,
        photoPageIndex:1,
        photoPageSize:9,
        albumOid:"",
        init: function() {
            this.pageIndex = 1;
            this.getList();
            this.bindEvent();
        },
        initPager:function(total){
            var _this = this;
            $('#pagination').pagination(total,{
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (pageIndex, jq) {
                    _this.pageIndex = pageIndex;
                    _this.getList(pageIndex);
                },
                items_per_page: this.pageSize //每页显示1项
            });
            this.pagerInited = true;
        },
        bindEvent: function() {
            var _this = this;
            $("#album_grid").on("click","#btn_add",function(e){
                e.preventDefault();
                _this.showAddDynamic("",{});
            });
            $("#album_grid").on("click", ".js-edit", function(e) {
                e.preventDefault();
                e.stopPropagation();
                var oid = $(e.currentTarget).closest("li").attr("id") || "";
                if (oid) {
                    _this.showUpdateDynamic(oid);
                }
            });
            $("#album_grid").on("click", ".js-del", function(e) {
                e.preventDefault();
                e.stopPropagation();
                var oid = $(e.currentTarget).closest("li").attr("id") || "";
                if (oid) {
                    _this.del(oid);
                }
            });
            $("#album_grid").on("mouseenter","tr",function(){
                $(this).find(".js-oper-btn").show();
            });
            $("#album_grid").on("mouseleave","tr",function(){
                $(this).find(".js-oper-btn").hide();
            });
            
            $("#album_grid").on("click", ".js-open-album", function(e) {
                e.preventDefault();
                e.stopPropagation();
                var oid = $(e.currentTarget).closest("li").attr("id") || "";
                _this.albumOid = oid;
                var title = $(e.currentTarget).next().html();
                if (oid) {
                    _this.showAlbum(oid, title);
                }
            });
            $("#searchAlbum").click(function(){
                _this.searchList();
            });
            $("#albumNameInput").on('keydown', function (e) {
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                    _this.searchList();
                }
            });

        },
        showUpdateDynamic: function(oid) {
            var dynamic;
            $.each(this.list, function(i, item) {
                if (item.po_photoId == oid) {
                    dynamic = item;
                    return false;
                }
            });
            if (!dynamic) {
                ui.showErrTip("未找到对象");
                return;
            }
            this.showAddDynamic(dynamic.po_photoId, dynamic);
        },
        //新增,编辑相册弹层
        showAddDynamic: function(oid, dynamic) {
            var title = oid ? "编辑相册" : "创建相册";
            var html = tmpl("add_album_tmpl", dynamic);
            var _this = this;
            var d = dialog({
                id:"save_ablum_dialog",
                title: title,
                content: html,
                width:720,
                height:400,
                onshow: function() {
                    ui.initSwitch("#albumInfo_isshow");
                    ui.initSwitch("#album_isshow");
                    require.async(["uploader"], function() {
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: G_CONFIG["api_prefix"] + "common/file/upload-image",
                            add:function(e,data){
                                data.submit();
                                $("#img_wrap").append('<div class="upload-process">上传中...</div>');
                            },
                            done: function(e, data) {
                                var res = data.result;
                                if (res.retCode == "0") {
                                    var img_url = res.data.path;
                                    $("#img_wrap").html('<img src="' + img_url + '" />');
                                    $("#picurl").val(img_url);
                                    $("#fileupload").nextAll(".js-err").html("");
                                } else {
                                    $("#fileupload").nextAll(".js-err").html("上传失败:" + res.errMsg);
                                    $("#picurl").val("");
                                }
                            }
                        });
                    });
                },
                ok: function() {
                    var title = ui.checkField("title", true, "相册名称不能为空");
                    var picurl = ui.checkField("picurl", true, "请上传相册封面图");
                    var info = ui.checkField("info");
                    var isshowinfo = $("#albumInfo_isshow").hasClass("switch-on") ? "1" : "0";
                    var display = $("#album_isshow").hasClass("switch-on") ? "1" : "0";
                    if (title === false || picurl === false) {
                        return false;
                    }
                    _this.save(oid,title,picurl,info,isshowinfo,display);
                    return false;
                },
                okValue: '保存',
                cancel: function() {
                }
                // ,button: [
                //     {
                //         value: '上传图片',
                //         callback: function () {
                //             d.close();
                //         },
                //         autofocus: true
                //     }
                // ]
            });
            d.showModal();
        },
        getList:function(pageIndex,title){
            if(typeof pageIndex == "undefined"){
                pageIndex = 1;
                this.pagerInited = false;
            }
            var url = api_prefix + "get-photo-album-list";
            var data = {
                pageIndex:pageIndex,
                pageSize:this.pageSize
            };
            if(title){
                data.title = title;
            }
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                data: data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.list = json.data.list || []; //列表
                        this.initTable(this.list);
                        if(!this.pagerInited){
                            this.initPager(json.data.total);
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
            ui.loading();
        },
        // 搜索相册
        searchList: function(){
            var val = $("#albumNameInput").val();
            this.pagerInited = false;
            this.getList(1,val);
        },
        initTable:function(list){
            var html = tmpl('album_row_tmpl', {list: list});
            $("#album_grid").html(html);
        },
        // 删除相册
        del:function(oid){
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "del-photo-album";
                    var data = {
                        po_photoId: oid
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: _this,
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                _this.getList(_this.pageIndex);
                                _this.pagerInited = false;
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        //添加、编辑相册
        save: function(oid,title,picurl,info,isshowinfo,display) {
            if(this.isSubmit){
                ui.showErrTip("请勿重复提交");
                return;
            }
            var url = api_prefix + "write-photo-album";
            var data = {
                title: title,
                picurl: picurl,
                info: info,
                isshowinfo: isshowinfo,
                display: display
            };
            if(oid){ //更新
                data.po_photoId = oid;
            }
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    this.isSubmit = false;
                    if (json.retCode == 0) {
                        dialog.get("save_ablum_dialog").remove();
                        ui.showSucTip("操作成功");
                        this.getList();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    this.isSubmit = false;
                }
            });
            this.isSubmit = true;
        },

        // 打开相册操作
        showAlbum: function(oid,title){
            var _this = this;
            this.getAlbumList();
            this.albumOid = oid;
            var html = document.getElementById('albumListBox');
            var d = dialog({
                title: title,
                content: html,
                width:780,
                height:520
            });
            d.showModal();
            this.bindPhotoEvent();
        },
        // 记录上传图片的数值
        picLength:0,
        picCount:0,
        picTotal:0,
        //上传图片
        fileUpload: function(title){
            var _this = this;
            //require.async(["plupload"], function() {
                var picIndex = 0;
                var url = api_prefix + "write-photo";
                var param = {
                    po_photoId: _this.albumOid,
                    display:1,
                    title:"",
                    picurl:"" 
                }
                // 收集上传后返回的对象
                var picArray = [];

                // 实例化一个plupload上传对象
                var uploader = new plupload.Uploader({
                    browse_button : 'fileupload2', //触发文件选择对话框的按钮，为那个元素id
                    url: G_CONFIG["api_prefix"] + "common/file/upload-image", //服务器端的上传页面地址
                    multi_selection: true,  // 多选
                    flash_swf_url : '/public/js/lib/plupload/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
                    silverlight_xap_url : '/public/js/lib/plupload/Moxie.xap' //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
                });    

                // 在实例对象上调用init()方法进行初始化
                uploader.init();

                // 当文件添加到上传队列后触发  绑定各种事件，并在事件监听函数中做你想做的事
                uploader.bind('FilesAdded',function(up,files){
                    _this.picLength = files.length;
                    uploader.start();
                    ui.loading(null,"正在上传...");
                });
                // 文件上传完成后触发
                uploader.bind('FileUploaded',function(up,files,responseObject){
                    var res = $.parseJSON(responseObject.response);
                    if (res.retCode == "0") {
                        var tit = files.name.replace(/\.\w+$/,"");
                        picArray.push({
                            po_photoId: _this.albumOid,
                            display:1,
                            title:tit,
                            picurl:res.data.path 
                        });
                        picIndex++;
                        if(picIndex === _this.picLength){
                            _this.getMorePic(picArray,up);
                        }
                    } else {
                        ui.showErrTip(res.errMsg);
                    }
                });
            //});
        },
        getMorePic: function(arr,uploader){
            var _this = this;
            var url = api_prefix + "write-photo";
            // 循环上传图片
            for(var i = 0, len = arr.length; i<len; i++){
                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: arr[i],
                    success: function(json) {
                        if (json.retCode == 0) {
                            _this.getAlbumList(1,true);
                        } else {
                            uploader.destroy();
                            _this.fileUpload();
                            ui.showErrTip(json.errMsg);
                        }
                    }
                });
            }
            // 需要重新计算分页
            this.photoPagerInited = false;
        },
        // 获取相册里的图片列表
        getAlbumList: function(pageIndex, isUpload, currentPage){
            if(typeof pageIndex == "undefined"){
                pageIndex = 1;
                this.photoPagerInited = false;
            }
            var data = {
                pageIndex:pageIndex,
                pageSize:this.photoPageSize
            };
            var url = api_prefix + "get-photo-list&po_photoId="+this.albumOid;
            util.myAjax({
                url: url,
                type: "GET",
                context: this,
                data: data,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.albumList = json.data.list || []; //列表 
                        this.initAlbumListTable(json.data.list,json.data);
                        this.picTotal = json.data.total;
                        // 判断是否是图片上传
                        if(!isUpload){
                            this.fileUpload();
                        }else {
                            this.picCount++;
                            if(this.picCount === this.picLength){
                                this.picCount = 0;
                                this.fileUpload();
                            }
                        }
                        if(!this.photoPagerInited){
                            this.initPhotoPager(json.data.total,currentPage); 
                        }
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
        },

        // 调用模板
        initAlbumListTable:function(list,head){
            var html = tmpl('photo_row_tmpl', {list: list});
            var head = tmpl('photo_head_tmpl', head);
            $("#photo_grid").html(html);
            $("#photo_head").html(head);
        },
        // 设置分页
        initPhotoPager:function(total,currentPage){
            var _this = this;
            $('#paginationPhoto').pagination(total,{
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (pageIndex, jq) {
                    _this.photoPageIndex = pageIndex;
                    _this.getAlbumList(pageIndex);
                },
                items_per_page: this.photoPageSize, //每页显示1项
                current_page: currentPage ? currentPage : 0
            });
            this.photoPagerInited = true;
        },
        // 删除图片
        delPhoto:function(oid){
            var _this = this;
            util.confirm("您确定要删除吗？", {
                ok: function() {
                    var url = api_prefix + "del-photo";
                    var data = {
                        po_photo_listId: oid
                    };
                    var currentPage = _this.photoPageIndex - 1;
                    var total = (_this.picTotal -1) % 9;
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: _this,
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                // 当删除到本页最后一项时,重新跳到第一页
                                if(total===0){
                                     _this.photoPageIndex = 1;
                                     _this.getAlbumList();
                                }else{
                                    _this.photoPagerInited = false;
                                    _this.getAlbumList(_this.photoPageIndex, false, currentPage);
                                }
                            } else {
                                ui.showErrTip(json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        // 设置封面图片
        setCover:function(photoOid, albumOid){
            var _this = this;
            var url = api_prefix + "set-album-cover";
            var data = {
                po_photo_listId: photoOid,
                po_photoId: albumOid
            };
            ui.loading(null,"正在设置...");
            util.myAjax({
                url: url,
                type: "POST",
                context: _this,
                data: data,
                success: function(json) {
                    if (json.retCode == 0) {
                        _this.getAlbumList();
                        _this.getList();
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                },
                complete:function(){
                    ui.removeLoading();
                }
            });
        },

        bindPhotoEvent: function() {
            var _this = this;
            $("#photo_grid").on("click", ".js-set", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("li").attr("id") || "";
                if (oid) {
                    _this.setCover(oid,_this.albumOid);
                }
            });
            $("#photo_grid").on("click", ".js-del", function(e) {
                e.preventDefault();
                var oid = $(e.currentTarget).closest("li").attr("id") || "";
                if (oid) {
                    _this.delPhoto(oid);
                }
            });
        }
    };
    module.exports = album;
});